<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '员工录单',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<template>
  <view class="px-3">
    <view class="rounded-3 overflow-hidden bg-white mt-3 py-3 text-center" v-if="showAICreate">
      <block v-if="!AICreating">
        <view class="font-bold">AI助手为您找到更更优方案</view>
        <view class="text-sm my-2">将[图片/语音]发过来帮你安排所有细节</view>
        <view class="grid grid-cols-3">
          <view
            class="text-center"
            v-for="(item, i) in panels"
            :key="item.title"
            @click="selectSheet(i)"
          >
            <image :src="item.iconUrl" mode="scaleToFill" class="w-8 h-8" />
            <view class="text-xs pt-1">{{ item.title }}</view>
          </view>
        </view>
      </block>
      <view v-if="AICreating" class="">
        <image :src="successIcon" mode="scaleToFill" class="w-20 h-20" />
        <view>已为您智能分析生成工单</view>
      </view>
    </view>

    <wd-form ref="form" :model="model" class="pt-3">
      <wd-cell-group border class="rounded-3 overflow-hidden">
        <wd-input
          label="姓名"
          label-width="100px"
          prop="ownerName"
          v-model="model.ownerName"
          :readonly="isReadonly"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <wd-input
          label="联系电话"
          label-width="100px"
          prop="ownerPhone"
          :readonly="isReadonly"
          v-model="model.ownerPhone"
          :maxlength="11"
          placeholder="请输入联系电话"
          :rules="[{ required: true, message: '请填写联系电话' }]"
        />
        <wd-select-picker
          prop="communityId"
          type="radio"
          label-width="100px"
          label="所属项目"
          :readonly="isReadonly"
          v-model="model.communityId"
          :columns="projectColumns"
          :rules="[{ required: true, message: '请选择所属项目' }]"
        ></wd-select-picker>
        <wd-select-picker
          prop="type"
          type="radio"
          label-width="100px"
          label="服务分类"
          :readonly="isReadonly"
          v-model="model.type"
          :columns="typeServeColumns"
          :rules="[{ required: true, message: '请选择服务分类' }]"
        ></wd-select-picker>
        <wd-select-picker
          prop="source"
          type="radio"
          label-width="100px"
          label="工单业务来源"
          :readonly="isReadonly"
          v-model="model.source"
          :columns="sourceColumns"
          :rules="[{ required: true, message: '请选择业务来源' }]"
        ></wd-select-picker>
        <wd-cell label-width="100px" title="是否加急">
          <wd-switch
            v-model="model.urgentFlag"
            :readonly="isReadonly"
            size="20px"
            :active-value="1"
            :inactive-value="0"
          />
        </wd-cell>
        <wd-textarea
          v-model="model.address"
          label="位置描述"
          label-width="100px"
          prop="address"
          :readonly="isReadonly"
          placeholder="请填写位置描述"
          :rules="[{ required: true, message: '请填写位置描述' }]"
        />
        <wd-textarea
          v-model="model.content"
          label="工单内容"
          label-width="100px"
          prop="content"
          placeholder="请填写工单内容"
          :readonly="isReadonly"
          :rules="[{ required: true, message: '请填写工单内容' }]"
        />
        <wd-cell label-width="100px" title="上传图片" vertical>
          <wd-upload
            :file-list="fileList"
            image-mode="aspectFill"
            :limit="1"
            :disabled="isReadonly"
            :action="actionUrl"
            @success="handleSuccess"
          ></wd-upload>
        </wd-cell>
      </wd-cell-group>
      <view class="footer py-6" v-if="!isReadonly">
        <wd-button type="primary" size="large" @click="handleSubmit" block>提 交</wd-button>
      </view>
    </wd-form>

    <!-- <RobotAi type="create" @create="handleRobot"></RobotAi> -->
  </view>

  <!-- <wd-action-sheet
    v-model="showCreateAction"
    title="AI助手为您找到更更优方案"
    :panels="panels"
    :lazy-render="false"
    @close="closeCreateAction"
    @select="selectSheet"
  /> -->

  <wd-popup v-model="showCreating" custom-style="border-radius:32rpx;" @close="handleCloseCreating">
    <view class="flex flex-col p-4 center">
      <view>
        <image :src="robotIcon" class="w-10 h-10" mode="scaleToFill" />
      </view>
      <view class="custom-txt">
        <view>· 正在分析工单内容</view>
        <view>· AI工单助手分析完成</view>
      </view>
    </view>
  </wd-popup>
</template>

<script lang="ts" setup>
import RobotAi from '@/components/robotAI.vue'
import { useToast } from 'wot-design-uni'
import robotIcon from '@/static/images/robot-icon.gif'
import pictureIcon from './static/image/picture-icon.svg'
import recordIcon from './static/image/record-icon.svg'
import photograph from './static/image/photograph.svg'
import successIcon from './static/image/success.svg'
import { createWorkOrder, IWorkOrderCreate, workOrderDetail, modifyWorkOrder } from './api/index'
import { typeServeColumns, projectColumns, sourceColumns } from './dict'
import { registerWeChat } from '@/utils/wecom'
import * as ww from '@wecom/jssdk'
import { generateRandomName } from '@/utils/index'

registerWeChat()

const id = ref('')
const isReadonly = computed(() => {
  return false
})

const toast = useToast()

const showAICreate = ref(false)
onLoad((options) => {
  id.value = options.id
  showAICreate.value = options.from === 'robot'
  // 存在id，获取详情
  if (id.value) {
    getDetail()
  }
})

const model = ref<IWorkOrderCreate>({
  ownerName: '',
  ownerPhone: '',
  communityId: 0,
  type: undefined,
  source: undefined,
  urgentFlag: 0,
  address: '',
  content: '',
  img: '',
  id: '',
})

const form = ref()
function handleSubmit() {
  form.value
    .validate()
    .then(async ({ valid, errors }) => {
      if (valid) {
        try {
          model.value.status = 1
          id.value ? await modifyWorkOrder(model.value) : await createWorkOrder(model.value)
          const name = generateRandomName()
          toast.success({
            msg: `工单创建成功，已分配${name}处理`,
            direction: 'vertical',
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } catch (error) {
          toast.error(error.msg)
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

async function getDetail() {
  const { data } = await workOrderDetail(id.value)

  for (const key in model.value) {
    model.value[key] = data[key]
  }
  if (data.img) {
    fileList.value.push({
      url: data.img,
    })
  }
}

const fileList = ref([])
const actionUrl = import.meta.env.VITE_UPLOAD_BASEURL
function handleSuccess({ file }) {
  const imgRes = JSON.parse(file.response)
  model.value.img = imgRes.url
}

const showCreateAction = ref<boolean>(false)

function handleRobot() {
  showCreateAction.value = true
}

function closeCreateAction() {
  showCreateAction.value = false
}

const panels = ref([
  {
    iconUrl: pictureIcon,
    title: '相册',
  },
  {
    iconUrl: photograph,
    title: '拍照',
  },
  {
    iconUrl: recordIcon,
    title: '语音',
  },
])

// 创建中
const showCreating = ref(false)
function handleCloseCreating() {
  showCreating.value = false
}

function selectSheet(index) {
  // toast.show(`当前选中项: ${item.title}, 下标: ${index}`)

  if ([0, 1].includes(index)) {
    handleChooseImage()
  }
  if (index === 2) {
    showCreating.value = true
  }
}

const AIForm = ref<IWorkOrderCreate>({
  ownerName: '刘伟',
  ownerPhone: '13673351890',
  communityId: 2,
  type: 4,
  source: 2,
  urgentFlag: 1,
  address: '儿童游乐区',
  content: '儿童游乐区地上有零食垃圾，已生成预处理工单，请尽快处理！',
  img: 'http://zz-ai-test.xinkt.com/profile/upload/2025/04/07/零食垃圾_20250407121115A002.jpg',
})

const AICreating = ref(false)
function handleChooseImage() {
  ww.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    defaultCameraMode: 'batch',
    isSaveToAlbum: true,
    success: (res: any) => {
      showCreating.value = true
      setTimeout(() => {
        model.value = AIForm.value
        fileList.value.push({
          url: AIForm.value.img,
        })

        handleCloseCreating()
        AICreating.value = true
      }, 2000)
    },
    fail: (res: any) => {
      console.log(res)
    },
  })
}
</script>

<style lang="scss" scoped></style>
